import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {WxgridService} from "./wxgrid.service";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {MsgResult} from "../../../../models/msg-result";
import {MsgConstants} from "../../../../constants/constants";

declare var $;
declare var BMap;
declare var BMapLib;
declare var BMAP_ANCHOR_TOP_RIGHT;

@Component({
  selector: 'app-wxgrid',
  templateUrl: './wxgrid.component.html'
})
export class WxgridComponent implements OnInit {
  @ViewChild('searchName') searchName:ElementRef;
  @ViewChild('pathDate') pathDate:ElementRef;

  map;

  listName :string = "网格站点";
  isGrid : boolean = true;
  gridType : string = "county";
  gridTypes : string = "county";
  siteType : string = "grid";
  maxHeight : string = "";
  nullSiteList : string = "加载更多";
  agentType : string = "grid";

  mapType : string = "map";
  gridDetailObj :any;
  defaultAnchor;
  defaultOffset;
  siteCacheArr :Array<object> = [];
  siteArr : Array<object> = [];
  clickNum : number = 1;
  count : number  = 15;
  isNormalMap : boolean = true;
  isTrack : boolean = false;
  isSingle : boolean = true;

  trackDeviceType :　string = "allDeviceType";
  trackType : string = "real";
  trackDeviceCode : string = "";
  trackSearchDate : string = "";
  checkNum : number = 0;
  trackHistoryArr : Array<any> = [];
  trackRealArr : Array<any> = [];
  lushuOverlays: Array<any> = [];
  lushuData: Array<any> = [];
  lushuStartAndEnd : Array<any> = [];
  lushuLine : Array<any> = [];
  lushuSpotrIcon: Array<any> = [];
  realMarker  = {marker:[],id:[]};
  testLushuPoint : Array<any> = [];
  testLushuColor : Array<any> = [];
  testLushuData;
  lushuClickElem;


  constructor(
    private wxGridService:WxgridService,
    private responseUtil :ResponseUtil,
    private dialogService: OneDialogService,
  ) { }

  ngOnInit() {
    this.initMapHeight();
    this.initMap();
    this.inputStyle();
    // this.zoomMap();
    this.domClick();
    // this.getMapSiteInfo();
    this.getMapGridInfo();
    this.initMapContentData();
    // this.mapTitle();
  }
  ngDoCheck(){
    if(this.isTrack){
      if(this.checkNum>1){
        return false;
      }else{
        if(this.pathDate){
          this.formatDateInfo(this.pathDate.nativeElement);
          this.checkNum++;
        }
      }
    }
  }
  initMapHeight = ()=>{
    let height = window.innerHeight;
    $(".one-notbreadcrumb").css("height",height-50+"px");
    this.maxHeight = height-300+"px";
  };
  /**
   * 初始化地图
   */
  initMap (){
    $("#map").css("height",window.innerHeight-50+"px");
    this.map = new BMap.Map("map",{enableMapClick:false,minZoom:5,maxZoom:18});
    let centerPoint = new BMap.Point(113.035508,34.941287);  // 创建点坐标
    this.map.centerAndZoom(centerPoint, 11);
    //地图样式
    let mapStyle = [
      {
        "featureType": "poi",
        "elementType": "all",
        "stylers": {
          "visibility": "on"
        }
      },
      {"featureType" : "land",
        "elementType": "geometry",
        "stylers": {
          "color": "#24252b"
        }
      },
      {"featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#171717",
          "weight": "0.1",
          "lightness": -6,
          "saturation": -15
        }
      },
      {
        "featureType": "highway",
        "elementType": "labels.icon",
        "stylers": {
          "visibility": "off"
        }
      },
      {"featureType": "building",
        "elementType": "geometry",
        "stylers": {
          "color": "#2a2b2e"
        }
      },
      {"featureType": "highway",
        "elementType": "all",
        "stylers": {
          "lightness": -42,
          "saturation": -91
        }
      },
      {"featureType": "arterial",
        "elementType": "geometry",
        "stylers": {
          "lightness": -77,
          "saturation": -94
        }
      },
      {"featureType": "green",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {"featureType": "subway",
        "elementType": "geometry.stroke",
        "stylers": {
          "color": "#181818"
        }
      },
      {"featureType": "railway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -52
        }
      },
      {"featureType": "all",
        "elementType": "labels.text.stroke",
        "stylers": {
          "color": "#313131"
        }
      },
      {"featureType": "all",
        "elementType": "labels.text.fill",
        "stylers": {
          "color": "#8b8787"
        }
      },
      {"featureType": "manmade",
        "elementType": "geometry",
        "stylers": {
          "color": "#1b1b1b"
        }
      },
      {"featureType": "local",
        "elementType": "geometry",
        "stylers": {
          "lightness": -75,
          "saturation": -91
        }
      },
      {"featureType": "subway",
        "elementType": "geometry",
        "stylers": {
          "lightness": -65
        }
      },
      {"featureType": "railway",
        "elementType": "all",
        "stylers": {
          "lightness": -40
        }
      },
      {"featureType": "road",
        "elementType": "geometry",
        "stylers": {
          "color": "#171717",
          "hue": "#041e3b",
          "weight": "1.0",
          "lightness": -12,
          "saturation": -15
        }
      },
      {"featureType": "water",
        "elementType": "geometry",
        "stylers": {
          "color": "#041e3b",
          "hue": "#041e3b",
          "weight": "0.1",
          "lightness": -12,
          "saturation": -15
        }
      }
    ];
    this.map.setMapStyle({styleJson:mapStyle});
    this.map.enableScrollWheelZoom();
    this.map.enableDragging();
  }
  initMapContentData(){
    this.testLushuPoint = [
      [{"lng":113.101189,"lat":34.913621},{"lng":113.101189,"lat":34.913621},{"lng":113.101169,"lat":34.913721},{"lng":113.101169,"lat":34.913721},{"lng":113.098935,"lat":34.913374},{"lng":113.097712,"lat":34.913183},{"lng":113.09671,"lat":34.913032},{"lng":113.094202,"lat":34.912646},{"lng":113.091893,"lat":34.912303},{"lng":113.08879,"lat":34.911834},{"lng":113.087294,"lat":34.911615},{"lng":113.085636,"lat":34.911371},{"lng":113.081745,"lat":34.910805},{"lng":113.079302,"lat":34.910447},{"lng":113.077724,"lat":34.910225},{"lng":113.076195,"lat":34.910002},{"lng":113.073148,"lat":34.909565},{"lng":113.070474,"lat":34.909171},{"lng":113.067921,"lat":34.908793},{"lng":113.067338,"lat":34.908712},{"lng":113.064816,"lat":34.90834},{"lng":113.062707,"lat":34.90803},{"lng":113.062727,"lat":34.907929},{"lng":113.062726,"lat":34.907928},{"lng":113.063016,"lat":34.906534},{"lng":113.063257,"lat":34.905341},{"lng":113.063287,"lat":34.9052},{"lng":113.063357,"lat":34.904859},{"lng":113.063627,"lat":34.903565},{"lng":113.063718,"lat":34.903154},{"lng":113.063738,"lat":34.903034},{"lng":113.063908,"lat":34.902222},{"lng":113.064059,"lat":34.901469},{"lng":113.064932,"lat":34.897147},{"lng":113.064952,"lat":34.897057},{"lng":113.064992,"lat":34.896836},{"lng":113.065444,"lat":34.89458},{"lng":113.065515,"lat":34.894249},{"lng":113.06641,"lat":34.889836},{"lng":113.066409,"lat":34.889834},{"lng":113.065294,"lat":34.889801},{"lng":113.063748,"lat":34.889673},{"lng":113.058328,"lat":34.88922},{"lng":113.052253,"lat":34.888658},{"lng":113.04997,"lat":34.888468},{"lng":113.047649,"lat":34.888233},{"lng":113.045989,"lat":34.888074},{"lng":113.0431,"lat":34.887779},{"lng":113.041173,"lat":34.887582},{"lng":113.03758,"lat":34.887199},{"lng":113.030265,"lat":34.886391},{"lng":113.028373,"lat":34.886154},{"lng":113.028383,"lat":34.886075},{"lng":113.028382,"lat":34.886074},{"lng":113.028753,"lat":34.88184},{"lng":113.028934,"lat":34.879843},{"lng":113.029125,"lat":34.877706},{"lng":113.029477,"lat":34.873322},{"lng":113.029688,"lat":34.871226},{"lng":113.029839,"lat":34.869648},{"lng":113.029515,"lat":34.865405},{"lng":113.029425,"lat":34.865124},{"lng":113.029425,"lat":34.865124},{"lng":113.026357,"lat":34.867148},{"lng":113.023649,"lat":34.868514}],
      [{"lng":113.073395,"lat":35.020498},{"lng":113.074963,"lat":35.020251},{"lng":113.08003,"lat":35.019452},{"lng":113.082916,"lat":35.019103},{"lng":113.085348,"lat":35.018973},{"lng":113.087619,"lat":35.018918},{"lng":113.088955,"lat":35.018909},{"lng":113.089617,"lat":35.01895},{"lng":113.089618,"lat":35.01895},{"lng":113.089768,"lat":35.017838},{"lng":113.089828,"lat":35.017407},{"lng":113.089949,"lat":35.016645},{"lng":113.090009,"lat":35.016574},{"lng":113.090009,"lat":35.016574},{"lng":113.090842,"lat":35.016653},{"lng":113.093532,"lat":35.016391},{"lng":113.096672,"lat":35.01602},{"lng":113.096672,"lat":35.016019},{"lng":113.096702,"lat":35.014709},{"lng":113.096742,"lat":35.012939},{"lng":113.096793,"lat":35.010959},{"lng":113.096874,"lat":35.007588},{"lng":113.096915,"lat":35.005698},{"lng":113.096926,"lat":35.005109},{"lng":113.096936,"lat":35.004409},{"lng":113.096936,"lat":35.004309},{"lng":113.097009,"lat":35.000499},{"lng":113.097019,"lat":34.999999},{"lng":113.09704,"lat":34.998849},{"lng":113.097081,"lat":34.997169},{"lng":113.097133,"lat":34.994959},{"lng":113.097135,"lat":34.99355},{"lng":113.096856,"lat":34.991343},{"lng":113.096786,"lat":34.990854},{"lng":113.096657,"lat":34.989845},{"lng":113.096647,"lat":34.989736},{"lng":113.096379,"lat":34.987749},{"lng":113.096349,"lat":34.987489},{"lng":113.09627,"lat":34.98686},{"lng":113.09616,"lat":34.986021},{"lng":113.095643,"lat":34.982118},{"lng":113.095304,"lat":34.979612},{"lng":113.094915,"lat":34.977066},{"lng":113.094885,"lat":34.976877},{"lng":113.094776,"lat":34.976118},{"lng":113.094716,"lat":34.975759},{"lng":113.094477,"lat":34.974102},{"lng":113.093297,"lat":34.968666},{"lng":113.093247,"lat":34.968417},{"lng":113.093177,"lat":34.968098},{"lng":113.092837,"lat":34.966512},{"lng":113.092677,"lat":34.965784},{"lng":113.092416,"lat":34.964568},{"lng":113.092356,"lat":34.964278},{"lng":113.092106,"lat":34.963122},{"lng":113.091946,"lat":34.962384},{"lng":113.091906,"lat":34.962235},{"lng":113.091866,"lat":34.962025},{"lng":113.091766,"lat":34.961546},{"lng":113.091763,"lat":34.961544},{"lng":113.091603,"lat":34.960806},{"lng":113.091372,"lat":34.960819},{"lng":113.091201,"lat":34.960761},{"lng":113.091041,"lat":34.960633},{"lng":113.090971,"lat":34.960444},{"lng":113.09097,"lat":34.960444},{"lng":113.090569,"lat":34.960439},{"lng":113.086742,"lat":34.960474},{"lng":113.086009,"lat":34.960485},{"lng":113.084099,"lat":34.960505},{"lng":113.084019,"lat":34.960507},{"lng":113.081164,"lat":34.960555},{"lng":113.080139,"lat":34.960572},{"lng":113.077062,"lat":34.960636},{"lng":113.076469,"lat":34.960647},{"lng":113.073503,"lat":34.960699},{"lng":113.071995,"lat":34.960725},{"lng":113.071925,"lat":34.960716},{"lng":113.071131,"lat":34.96069},{"lng":113.069502,"lat":34.960617},{"lng":113.069221,"lat":34.960572},{"lng":113.06922,"lat":34.960572},{"lng":113.068245,"lat":34.960427},{"lng":113.068185,"lat":34.960538},{"lng":113.068064,"lat":34.96065},{"lng":113.067873,"lat":34.960733},{"lng":113.067783,"lat":34.960755},{"lng":113.067662,"lat":34.960767},{"lng":113.067441,"lat":34.96073},{"lng":113.06723,"lat":34.960614},{"lng":113.06711,"lat":34.960426},{"lng":113.06712,"lat":34.960186},{"lng":113.067221,"lat":34.960034},{"lng":113.067391,"lat":34.959911},{"lng":113.067582,"lat":34.959859},{"lng":113.067773,"lat":34.959856},{"lng":113.067773,"lat":34.959855},{"lng":113.067713,"lat":34.959006},{"lng":113.067612,"lat":34.957478},{"lng":113.067461,"lat":34.95268},{"lng":113.067441,"lat":34.952121},{"lng":113.067391,"lat":34.951021},{"lng":113.06731,"lat":34.949292},{"lng":113.06731,"lat":34.949213},{"lng":113.067199,"lat":34.947014},{"lng":113.067179,"lat":34.946624},{"lng":113.067097,"lat":34.944935},{"lng":113.066904,"lat":34.940488},{"lng":113.066904,"lat":34.940408},{"lng":113.066659,"lat":34.93626},{"lng":113.066658,"lat":34.936259},{"lng":113.066517,"lat":34.935181},{"lng":113.066386,"lat":34.935143},{"lng":113.066326,"lat":34.935094},{"lng":113.066276,"lat":34.934975},{"lng":113.066306,"lat":34.934875},{"lng":113.066305,"lat":34.934874},{"lng":113.063753,"lat":34.934172},{"lng":113.059435,"lat":34.932956},{"lng":113.058633,"lat":34.932804},{"lng":113.05777,"lat":34.932833},{"lng":113.057048,"lat":34.93287},{"lng":113.055123,"lat":34.932987},{"lng":113.054271,"lat":34.933013},{"lng":113.053059,"lat":34.933101},{"lng":113.051406,"lat":34.93321},{"lng":113.050916,"lat":34.933192},{"lng":113.050595,"lat":34.933143},{"lng":113.048904,"lat":34.932829},{"lng":113.044972,"lat":34.93208},{"lng":113.042883,"lat":34.931685},{"lng":113.039248,"lat":34.930978},{"lng":113.03446,"lat":34.930037},{"lng":113.033414,"lat":34.929845},{"lng":113.032328,"lat":34.929813},{"lng":113.031381,"lat":34.929791}],
      [{"lng":113.10132,"lat":34.91364},{"lng":113.103132,"lat":34.913923},{"lng":113.105504,"lat":34.914298},{"lng":113.105624,"lat":34.914308},{"lng":113.105604,"lat":34.914408},{"lng":113.105604,"lat":34.914408},{"lng":113.104601,"lat":34.922332},{"lng":113.104075,"lat":34.926494},{"lng":113.103608,"lat":34.930236},{"lng":113.103441,"lat":34.932697},{"lng":113.103421,"lat":34.933008},{"lng":113.102966,"lat":34.939981},{"lng":113.102907,"lat":34.940771},{"lng":113.102828,"lat":34.941962},{"lng":113.102749,"lat":34.943032},{"lng":113.102709,"lat":34.943612},{"lng":113.102639,"lat":34.944633},{"lng":113.1026,"lat":34.945163},{"lng":113.102471,"lat":34.946744},{"lng":113.102461,"lat":34.946824},{"lng":113.102341,"lat":34.948385},{"lng":113.102232,"lat":34.949735},{"lng":113.102082,"lat":34.951746},{"lng":113.101712,"lat":34.956088},{"lng":113.101702,"lat":34.956218},{"lng":113.101692,"lat":34.956278},{"lng":113.101512,"lat":34.959888},{"lng":113.101492,"lat":34.960319},{"lng":113.101462,"lat":34.960399},{"lng":113.101381,"lat":34.960399},{"lng":113.101379,"lat":34.960399},{"lng":113.101199,"lat":34.96039},{"lng":113.100428,"lat":34.960394},{"lng":113.099226,"lat":34.960392},{"lng":113.098164,"lat":34.960389},{"lng":113.096429,"lat":34.960394},{"lng":113.095376,"lat":34.960404},{"lng":113.095376,"lat":34.960403},{"lng":113.092496,"lat":34.960425},{"lng":113.092175,"lat":34.960479},{"lng":113.091894,"lat":34.960642},{"lng":113.091784,"lat":34.960733},{"lng":113.091603,"lat":34.960806},{"lng":113.091603,"lat":34.960806},{"lng":113.091763,"lat":34.961544},{"lng":113.091863,"lat":34.962022},{"lng":113.091903,"lat":34.962232},{"lng":113.091943,"lat":34.962381},{"lng":113.092104,"lat":34.963119},{"lng":113.092354,"lat":34.964276},{"lng":113.092414,"lat":34.964565},{"lng":113.092675,"lat":34.965782},{"lng":113.092835,"lat":34.96651},{"lng":113.093175,"lat":34.968096},{"lng":113.093245,"lat":34.968415},{"lng":113.093295,"lat":34.968664},{"lng":113.094475,"lat":34.9741},{"lng":113.094715,"lat":34.975757},{"lng":113.094775,"lat":34.976116},{"lng":113.094884,"lat":34.976875},{"lng":113.094914,"lat":34.977065},{"lng":113.095303,"lat":34.97961},{"lng":113.095642,"lat":34.982116},{"lng":113.096159,"lat":34.98602},{"lng":113.096269,"lat":34.986859},{"lng":113.096348,"lat":34.987488},{"lng":113.096378,"lat":34.987747},{"lng":113.096647,"lat":34.989734},{"lng":113.096657,"lat":34.989844},{"lng":113.096786,"lat":34.990853},{"lng":113.096856,"lat":34.991342},{"lng":113.097135,"lat":34.993549},{"lng":113.097133,"lat":34.994959},{"lng":113.097081,"lat":34.997169},{"lng":113.09704,"lat":34.998848},{"lng":113.097019,"lat":34.999998},{"lng":113.097009,"lat":35.000498},{"lng":113.096937,"lat":35.004308},{"lng":113.096937,"lat":35.004408},{"lng":113.096926,"lat":35.005108},{"lng":113.096916,"lat":35.005698},{"lng":113.096875,"lat":35.007588},{"lng":113.096794,"lat":35.010959},{"lng":113.096743,"lat":35.012939},{"lng":113.096703,"lat":35.014709},{"lng":113.096673,"lat":35.016019},{"lng":113.096643,"lat":35.01762},{"lng":113.096634,"lat":35.01797},{"lng":113.096544,"lat":35.022281},{"lng":113.096505,"lat":35.023982},{"lng":113.096485,"lat":35.024802},{"lng":113.096456,"lat":35.026172},{"lng":113.096446,"lat":35.026382},{"lng":113.096467,"lat":35.027272},{"lng":113.096478,"lat":35.028452},{"lng":113.096608,"lat":35.029231},{"lng":113.09686,"lat":35.030069},{"lng":113.097282,"lat":35.031066},{"lng":113.097723,"lat":35.031883},{"lng":113.09955,"lat":35.03499},{"lng":113.09968,"lat":35.0352},{"lng":113.09973,"lat":35.035279},{"lng":113.100352,"lat":35.036366},{"lng":113.101025,"lat":35.037553},{"lng":113.101717,"lat":35.03911},{"lng":113.102018,"lat":35.039919},{"lng":113.102016,"lat":35.039919},{"lng":113.100845,"lat":35.039924},{"lng":113.098931,"lat":35.040096},{"lng":113.098501,"lat":35.040109},{"lng":113.097709,"lat":35.040145},{"lng":113.097308,"lat":35.040148},{"lng":113.097067,"lat":35.04015},{"lng":113.096536,"lat":35.040175},{"lng":113.09439,"lat":35.040146},{"lng":113.092493,"lat":35.040047},{"lng":113.090656,"lat":35.04003},{"lng":113.079652,"lat":35.039773},{"lng":113.076093,"lat":35.039755},{"lng":113.073629,"lat":35.039749},{"lng":113.070261,"lat":35.039737},{"lng":113.068101,"lat":35.039732},{"lng":113.060658,"lat":35.039528},{"lng":113.060656,"lat":35.039527},{"lng":113.060514,"lat":35.037888},{"lng":113.060453,"lat":35.037089},{"lng":113.059323,"lat":35.02799},{"lng":113.05895,"lat":35.025004}]
    ];
    this.testLushuColor = ["#89b3cb","#df9d68","#160bb1"];
  }
  /**
   * 地图缩放(暂不使用)
   */
  zoomMap(){
    this.map.addEventListener("zoomend",function(){
      if(this.mapType=="map" &&　this.siteType == "grid"){
        let mapLevel = this.map.getZoom();
        let lastGridType = this.gridType;
        this.gridType =mapLevel<11?"county":mapLevel == 12?"town":mapLevel== 13 ?"village":mapLevel >= 14?"group":"county";
        if(lastGridType != this.gridType){
          this.getMapGridInfo();
        }
      }
    }.bind(this))
  }
  /**
   * 修改input样式
   */
  inputStyle =() =>{
    $(".stateChoose").iCheck({
      checkboxClass: 'icheckbox_minimal-green',
      radioClass: 'iradio_minimal-green',
      increaseArea: '20%' // optional
    })
  }
  /*
   * 地图类型点击效果
   */
  mapTypeClick =(mapType)=>{
    this.map.setMinZoom(5);
    if(this.mapType == mapType){
      return false;
    }else{
      this.mapType = mapType;
      this.clearData();
      this.clearAllLabel();
      if(mapType == "map"){
        this.isSingle = true;
        this.agentType = "grid";
        this.isGrid = true;
        this.isNormalMap  = true;
        this.siteType = "grid";
        this.isTrack = false;
        this.map.setZoom(11);
        if(this.map.getZoom() == 11){
          this.gridType = "county";
          this.gridTypes = "county";
          this.getMapGridInfo();
        }
      }else if(mapType == "track"){
        this.clearLushuData();
        this.isNormalMap  = false;
        this.isTrack = true;
        this.checkNum = 0;
        this.trackType = "real";
        this.map.setZoom(12);
        this.getTrackDeviceList();
      }
    }
  };
  /*
   *管理类型点击
   */
  agentClick(type){
    if(this.agentType == type){
      return false;
    }else{
      this.agentType = type;
      if(type == "grid"){
        this.isGrid = true;
        this.siteType = "grid";
        this.map.setZoom(11);
        if(this.map.getZoom() == "11"){
          let mapLevel = this.map.getZoom();
          this.gridType =mapLevel<11?"county":mapLevel == 12?"town":mapLevel== 13 ?"village":mapLevel >= 14?"group":"county";
          this.getMapGridInfo();
        }else{
          this.map.setZoom(11);
        }
        this.maxHeight = window.innerHeight-290+"px";
        this.listName = "网格站点";
      }else{
        this.isGrid = false;
        this.map.setZoom(12);
        this.siteType = "industrySite";
        this.listName = "企业名称";
        this.getMapSiteInfo();
        this.maxHeight = window.innerHeight-330+"px";
      }
    }
  }
  /*
  *站点类型点击
   */
  siteClick = (elem,type)=>{
    this.siteType = type;
    if($(elem).find(".one-site-img").hasClass("active")){
      return false;
    }else if(this.agentType=="pollute"){
      this.isGrid = false;
      if(type == "industrySite"){
        this.listName = "企业名称";
      }else if(type == "waterPollutionSite"){
        this.listName = "企业名称";
      }else if(type == "smallAirSite"){
        this.listName = "监测站点";
      }else if(type == "waterSurfaceSite"){
        this.listName = "监测站点";
      }else if(type == "enterprises"){
        this.listName = "企业名称";
      }
      this.siteType =="enterprises"?this.getGridEnterprise(): this.getMapSiteInfo();
    }else if(this.agentType=="grid"){
      if(type == "grid"){
        this.listName = "网格站点";
        this.isGrid = true;
        if(this.map.getZoom() == "11"){
          let mapLevel = this.map.getZoom();
          this.gridType =mapLevel<11?"county":mapLevel == 12?"town":mapLevel== 13 ?"village":mapLevel >= 14?"group":"county";
          this.getMapGridInfo();
        }else{
          this.map.setZoom(11);
        }
      }
    }
  };
  /*
   *多选单选的选择框点击
   */
  singleOrMultiple(even){
    if($(even.target).prev().is(":checked")){
      this.isSingle = true;
      let siteTypeArr = this.gridTypes.split(",");
      this.gridType = siteTypeArr[siteTypeArr.length-1];
      this.gridTypes = this.gridType;
      this.clearData();
      this.clearAllLabel();
      this.getMapGridInfo();
    }else{
      this.isSingle = false;
    }
  }

  /*
   *清除数据
   */
  clearData(){
    this.siteArr = [];
    this.siteCacheArr = [];
    this.clickNum = 1;
    this.nullSiteList = "正在加载";
  }
  /*
   *清除所有标注
   */
  clearAllLabel() {
    this.map.clearOverlays();
  }

  /*
   *清除部分标注
   */
  clearPartLabel(type) {
    if (this.map.getOverlays().length) {
      this.map.getOverlays().forEach((elem, i) => {
        if (elem.content && elem.content.indexOf(type) != -1) {
          this.map.removeOverlay(elem);
        }
      })
    }
  }
  /*
  * 选择网格
   */
  gridClick = (elem,type) =>{
    this.gridType = type;
    if($(elem).hasClass("active")){
      if(this.isSingle){
        return false;
      }else{
        if(this.gridTypes.indexOf(",") != -1){
          if (this.gridTypes.indexOf(this.gridType) == 0) {
            this.gridTypes = this.gridTypes.replace(this.gridType + ",", "");
          } else {
            this.gridTypes = this.gridTypes.replace("," + this.gridType, "");
          }
          this.clearPartLabel(this.gridType);
        }else{
          return false;
        }
      }
    }else{
      if(type =="county"){
        this.map.setZoom(11);
      }else if(type =="town"){
        this.map.setZoom(12);
      }else if(type =="village"){
        this.map.setZoom(13);
      }else if(type =="group"){
        this.map.setZoom(14);
      }
      if(this.isSingle){
        this.gridTypes = type;
      }else{
        this.gridTypes += ","+type;
      }
      this.getMapGridInfo();
    }
  }
  /*
   * 添加标注
   */
   mapLabel(dataObj){
     let smallAirImg : Array<string>= ["marker_v1_0.png","marker_v1_1.png","marker_v1_2.png","marker_v1_3.png","marker_v1_4.png","marker_v1_5.png","marker_v1_9.png"];
     let img = "";
     let aqi = "";
     if(dataObj.siteStatus == "1111" || dataObj.pointType=="grid" || dataObj.pointType=="enterprises"){
       if(dataObj.pointType == "waterSurfaceSite"){
         img = "ico-waterSurface.png";
         dataObj.className = "one-bg-level-default"
       }else if(dataObj.pointType == "waterPollutionSite"){
         img = "ico-waterPollution.png";
         dataObj.className = "one-bg-level-default"
       }else if(dataObj.pointType == "industrySite"){
         img = "ico-industry.png";
         dataObj.className = "one-bg-level-default"
       }else if(dataObj.pointType == "smallAirSite"){
         let i = this.aqiLevel(dataObj.aqi)-1;
         img = smallAirImg[i];
         aqi = dataObj.aqi;
         dataObj.className = "one-bg-level"+(i+1);
       }else if(dataObj.pointType == "enterprises"){
         img = "ico-polluting-enterprises.png";
         dataObj.className = "one-bg-level-default";
       }else if(dataObj.pointType == "grid"){
         img = "ico-grid.png";
         dataObj.className = "one-bg-level-default";
       }
     }else{
       img = "icon-" + dataObj.pointType + "-lost.png";
       aqi = dataObj.pointType == "smallAirSite" ? "-" : "";
       dataObj.className = "one-bg-level7";
     }
     let siteType = dataObj.pointType == "grid"?dataObj.gridType : dataObj.pointType;
     let markerPoint = new BMap.Point(dataObj.longitude,dataObj.latitude);  // 创建点坐标 ;
     let myLabel = new BMap.Label("<div class='one-site-label-name' style='display:block;top: -27px;'>"+(dataObj.siteName || dataObj.regionName||dataObj.enterpriseName)+"</div><span id='"+(dataObj.siteCode || dataObj.regionCode)+"' class='"+siteType+" labelData"+"' style='color:#fff;display: inline-block;'>"+aqi+"</span>",    //为lable填写内容margin-left: -3px;
       {offset:new BMap.Size(-21,-51),               //label的偏移量，为了让label的中心显示在点上
         position:markerPoint});                                //label的位置
     myLabel.setStyle({                                   //给label设置样式，任意的CSS都是可以的
       maxWidth:42+"px",
       width:42+"px",  //宽
       display:"inline-block",
       fontSize:"14px",               //字号
       border:"0",                    //边
       height:51+"px",                //高度
       textAlign:"center",            //文字水平居中显示
       lineHeight:51-8+"px",
       background:"url(../../../../../assets/v1/css/dam/realTime/mapImg/"+img+") no-repeat",    //背景图片
       cursor:"pointer"
     });
     myLabel.setTitle(dataObj.siteName || dataObj.regionName ||dataObj.enterpriseName );                 //为label添加鼠标提示
     this.map.addOverlay(myLabel);
     myLabel.addEventListener("click",function(e){
       this.infoWindowEvent(dataObj,"map");
     }.bind(this))
  }
  /*
   * aqi等级
   */
  aqiLevel = (data) => {
    return data<=50?1
      :data>50&&data<=100?2
        :data>100&&data<=150?3
          :data>150&&data<=200?4
            :data>200&&data<=300?5
              :data>300?6:7;
  };
  /*
   * 信息窗口
   */
  infoWindowEvent(dataObj,type){
    if(dataObj.pointType != "grid"){
      let option = {offset:new BMap.Size(5,-26),width:350};
      let html = "";
      html = dataObj.pointType =="industrySite"?this.industrySiteHtml(dataObj):dataObj.pointType =="smallAirSite"?this.allNationSiteSmallHtml(dataObj):dataObj.pointType =="waterPollutionSite"?this.waterPollutionHtml(dataObj):dataObj.pointType =="waterSurfaceSite"?this.waterSurfaceHtml(dataObj):dataObj.pointType =="enterprises"?this.industryInfoWindowHtml(dataObj):"暂无数据";
      let infoWindow = new BMap.InfoWindow(html,option);
      infoWindow.addEventListener("open",function(open){
        $(".realVideo").click(function(){
          $(".one-map-real-video").show();
        });
      }.bind(this));
      infoWindow.addEventListener("close",function(open){
        $(".one-map-real-video").hide();
      }.bind(this));
      let point = new BMap.Point(dataObj.longitude,dataObj.latitude);
      type == "list" && this.map.centerAndZoom(point,this.map.getZoom());
      this.map.openInfoWindow(infoWindow,point);
    }else{
      this.gridDetailObj = dataObj;
      this.gridDetailObj.type = type;
      this.getMapGridDetailInfo(dataObj.regionCode)
    }
  }
  closeParent = (elem) =>{
    $(elem).parent().parent().hide();
  };
  /*
   * 信息窗口Html
   */
  //企业信息窗口html
  industryInfoWindowHtml(dataObj){
    return `
      <div class="one-info-window">
         <div class="one-info-content">
           <div class="one-info-content-header">               
             <span>${dataObj.enterpriseName}</span>
             <button class="btn btn-success pull-right realVideo">实时视频</button>
           </div>
           <div class="one-info-content-body one-grid-content-body" style="padding: 0 10px;">       
             <ul class="list-inline">
               <li style="width: 96px;">法人：</li>
               <li>${dataObj.businessEntity || "-"}</li> 
             </ul>
              <ul class="list-inline">
               <li style="width: 96px;">电话：</li>
               <li>${dataObj.phone || "-"}</li>        
             </ul>  
              <ul class="list-inline">
               <li style="width: 96px;">主管环保经理：</li>
               <li>${dataObj.greenManager || "-"}</li>       
             </ul>
              <ul class="list-inline">
               <li style="width: 96px;">主要产品：</li>
               <li>${dataObj.majorProduct || "-"}</li>       
             </ul>
              <ul class="list-inline">
               <li style="width: 96px;">污染因子：</li>
               <li>${dataObj.contaminant || "-"}</li> 
             </ul>  
             <ul class="list-inline">
               <li style="width: 96px;">片区：</li> 
               <li>${dataObj.address || "-"}</li>        
             </ul>                  
             <ul class="list-inline">  
               <li style="width: 96px;">包乡人员：</li>       
               <li>${dataObj.responsible || "-"}</li>        
             </ul>   
           </div>
         </div>
      </div>
    `;
  }
  //空气质量信息窗口html
  airQualityInfoWindowHtml(dataObj){
    return `
      <div class="one-info-window">
         <div class="one-info-content">
           <div class="one-info-content-header">               
             <span>${dataObj.siteName}</span>
             <button class="btn btn-success pull-right realVideo">实时视频</button>
           </div>
           <div class="one-info-content-body one-grid-content-body">
             <ul class="list-inline">
               <li>站点位置：</li>
               <li>鑫源中路101 </li>       
             </ul>
              <ul class="list-inline">
               <li>责任单位：</li>
               <li>县直企业 </li>       
             </ul>
             <ul class="list-inline">
               <li>污染程度：</li>
               <li>${dataObj.aqiLevelType}</li>                         
             </ul>
             <div class="one-site-pollute-data">
              <ul class="list-inline"> 
                <li class="one-site-pollute-level${this.aqiLevel(dataObj.pm25IAQI)}"> 
                  <ul class="test">
                    <li>${dataObj.pm25}</li> 
                    <li class="one-text-small">PM2.5</li> 
                  </ul> 
                </li>
                <li class="one-site-pollute-level${this.aqiLevel(dataObj.pm10IAQI)}">
                  <ul class="test">
                    <li>${dataObj.pm10}</li> 
                    <li class="one-text-small">PM10</li> 
                  </ul> 
                </li> 
                <li class="one-site-pollute-level${this.aqiLevel(dataObj.so2IAQI)}">
                   <ul class="test">
                    <li>${dataObj.so2}</li>
                    <li class="one-text-small">SO2</li> 
                   </ul> 
                </li> 
                <li class="one-site-pollute-level${this.aqiLevel(dataObj.no2IAQI)}"> 
                   <ul class="test">
                    <li>${dataObj.no2}</li> 
                    <li class="one-text-small">NO2</li> 
                   </ul> 
                </li> 
                <li class="one-site-pollute-level${this.aqiLevel(dataObj.coIAQI)}">
                   <ul class="test">
                     <li>${dataObj.co}</li> 
                     <li class="one-text-small">CO</li> 
                   </ul>
                </li> 
                <li class="one-site-pollute-level${this.aqiLevel(dataObj.o3IAQI)}"> 
                   <ul class="test"> 
                      <li>${dataObj.o3}</li> 
                      <li class="one-text-small">O3</li> 
                   </ul> 
                </li> 
              </ul> 
             </div>
           </div>
         </div>
      </div>
    `;
  }
  //水环境质量信息窗口html
  waterInfoWindowHtml(dataObj){
    return `
      <div class="one-info-window">
         <div class="one-info-content">
           <div class="one-info-content-header">               
             <span>${dataObj.siteName}</span>
             <button class="btn btn-success pull-right realVideo">实时视频</button>
           </div>
           <div class="one-info-content-body one-grid-content-body">
             <ul class="list-inline">
               <li>站点位置：</li>
               <li>鑫源中路101 </li>       
             </ul>
              <ul class="list-inline">
               <li>责任单位：</li>
               <li>县直企业 </li>       
             </ul>
             <ul class="list-inline">
               <li>污染程度：</li>
               <li>重度污染</li>       
             </ul>
             <div class="one-site-pollute-data">
              <ul class="list-inline"> 
                <li class="one-site-water-type"> 
                  <ul class="test">
                    <li>${dataObj.AvgStrength001}</li> 
                    <li class="one-text-small">COD</li> 
                  </ul> 
                </li>
                <li class="one-site-water-type">
                  <ul class="test">
                    <li>${dataObj.AvgStrength002}</li> 
                    <li class="one-text-small">氨氮</li> 
                  </ul> 
                </li> 
                <li class="one-site-water-type">
                   <ul class="test">
                    <li>${dataObj.AvgStrength003}</li>                
                    <li class="one-text-small">总磷</li> 
                   </ul> 
                </li> 
              </ul> 
             </div>
           </div>
         </div>
      </div>
    `;
  }
  //网格信息窗口html
  gridWindowHtml(dataObj,name){
    let adminHtml:string = "",memberHtml:string='',deputyHtml:string ="",inspectorHtml:string = "",superviseHtml:string='',powerHtml:string ="";
    adminHtml = this.gridDetailHtml(dataObj.adminList,"网格长");
    memberHtml = this.gridDetailHtml(dataObj.memberList,"网格员");
    deputyHtml = this.gridDetailHtml(dataObj.deputyList,"副网格长");
    inspectorHtml = this.gridDetailHtml(dataObj.inspectorList,"巡查员");
    superviseHtml = this.gridDetailHtml(dataObj.superviseList,"监督员");
    powerHtml = this.gridDetailHtml(dataObj.powerList,"供电员");
    return `
      <div class="one-info-window">
         <div class="one-info-content">
           <div class="one-info-content-header">               
             <span>${name}</span>  
             <button class="btn btn-success pull-right gridDuty">网格职责</button> 
           </div>
           <div class="one-info-content-body one-grid-content-body one-grid-bordered">          
            <ul class="list-inline">
               <li></li>
               <li>
                  <ul class="list-inline one-map-grid-info">
                    <li>姓名</li>  
                    <li>职位</li> 
                    <li>联系电话</li> 
                  </ul>
                  <ul class="list-inline one-map-grid-info">
                    <li>姓名</li>  
                    <li>职位</li>     
                    <li>联系电话</li> 
                  </ul>  
               </li>
            </ul>
            ${adminHtml} 
            ${deputyHtml} 
            ${memberHtml} 
            ${inspectorHtml} 
            ${superviseHtml} 
            ${powerHtml} 
           </div>
         </div>
      </div>
    `;
  }
  //根据数据生成网格html
  gridDetailHtml(dataObj,type){
    let dutyList = "";
    dutyList = type=="网格长"?"adminList":type=="网格员"?"memberList":type=="副网格长"?"deputyList":type=="巡查员"?"inspectorList":type=="监督员"?"superviseList":type=="供电员"?"powerList":"";
    if(dataObj.length){
      let gridInfoHtml:string = '';
      dataObj.forEach((data,i)=>{
        gridInfoHtml += `
        <ul class="list-inline one-map-grid-info">
           <li>${data.name || "-"}</li>
           <li>${data.duty || "-"}</li>        
           <li>${data.mobilePhone || "-"}</li>            
        </ul>
        `;
      });
      return  `
        <ul class="list-inline">
           <li class="gridPeopleDuty" data-list="${dutyList}">${type}</li>     
           <li>
             ${gridInfoHtml} 
           </li>        
        </ul>
        `
    }else{
      return '';
    }
  }

  //标准站/小型站详细信息
  allNationSiteSmallHtml(dataObj){
  let name = "";
  name = dataObj.siteName;
  dataObj.aqiLevelType = dataObj.aqiLevelType?dataObj.aqiLevelType:"暂无等级类型";
    return '<div class="one-info-window"> <div class="one-info-content-header"><span >'+dataObj.siteName+' </span><div class="pull-right one-site-time-black">'+dataObj.monitorTime+' </div> </div> <div class="one-site-info-body one-grid-info-body"> <div class="pull-left"> <div style="font-size: 32px;">'+dataObj.aqi+'</div> <div class="one-bg-level'+this.aqiLevel(dataObj.aqi)+'">'+dataObj.aqiLevelType+'</div> </div> <div class="pull-right"> <ul class="list-unstyled"> <li>温度：<span>'+dataObj.temp+'</span>&degC</li> <li>湿度：<span>'+dataObj.hum+'</span>%</li> <li>'+dataObj.windDirection+dataObj.windSpeed+'</li> </ul> </div> </div> <div class="one-site-pollute-data"> <ul class="list-inline"> <li class="one-site-pollute-level'+this.aqiLevel(dataObj.pm25IAQI)+'"> <ul class="test"> <li>'+dataObj.pm25+'</li> <li class="one-text-small">PM2.5</li> </ul> </li> <li class="one-site-pollute-level'+this.aqiLevel(dataObj.pm10IAQI)+'"> <ul class="test"><li>'+dataObj.pm10+'</li> <li class="one-text-small">PM10</li> </ul> </li> <li class="one-site-pollute-level'+this.aqiLevel(dataObj.so2IAQI)+'"> <ul class="test"> <li>'+dataObj.so2+'</li> <li class="one-text-small">SO2</li> </ul> </li> <li class="one-site-pollute-level'+this.aqiLevel(dataObj.no2IAQI)+'"> <ul class="test"> <li>'+dataObj.no2+'</li> <li class="one-text-small">NO2</li> </ul> </li> <li class="one-site-pollute-level'+this.aqiLevel(dataObj.coIAQI)+'"> <ul class="test"> <li>'+dataObj.co+'</li> <li class="one-text-small">CO</li> </ul> </li> <li class="one-site-pollute-level'+this.aqiLevel(dataObj.o3IAQI)+'"> <ul class="test"> <li>'+dataObj.o3+'</li> <li class="one-text-small">O3</li> </ul> </li> </ul> </div></div> ';
}
  //工业废气详细信息
  industrySiteHtml(dataObj){
    return '<div class="one-info-window"><div class="one-info-content-header"> <span >'+dataObj.siteName+'</span> <div class="pull-right one-site-time-black">'+dataObj.monitorTime+'</div></div><div class="one-site-pollute-data"> <ul class="list-inline"> <li class="one-site-smoke-type-black"> <ul class="test"> <li>'+dataObj.AvgStrength001+'</li> <li class="one-text-small">烟尘</li> </ul> </li> <li class="one-site-pollute-level2"> <ul class="test"> <li>'+dataObj.AvgStrength002+'</li> <li class="one-text-small">SO2</li> </ul> </li> <li class="one-site-pollute-level3"> <ul class="test"> <li>'+dataObj.AvgStrength003+'</li> <li class="one-text-small">NO<sub>x</sub></li> </ul> </li> </ul> </div>  </div>';
}
  //工业废水详细信息
  waterPollutionHtml(dataObj){
    return '<div class="one-info-window"><div class="one-info-content-header"> <span >'+dataObj.siteName+'</span> <div class="pull-right one-site-time-black">'+dataObj.monitorTime+'</div></div> <div class="one-site-pollute-data"> <ul class="list-inline"> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength001+'</li> <li class="one-text-small">COD</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength002+'</li> <li class="one-text-small">氨氮</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength003+'</li> <li class="one-text-small">总磷</li> </ul> </li> </ul> </div></div>';
}
  //水质断面详细信息
  waterSurfaceHtml(dataObj){
    return '<div class="one-info-window"><div class="one-info-content-header"> <span >'+dataObj.siteName+'</span> <div class="pull-right one-site-time-black">'+dataObj.monitorTime+'</div></div><div class="one-site-pollute-data"> <ul class="list-inline"> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength001+'</li> <li class="one-text-small">COD</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength002+'</li> <li class="one-text-small">氨氮</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength003+'</li> <li class="one-text-small">总磷</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength004+'</li> <li class="one-text-small">总氮</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength005+'</li> <li class="one-text-small">TOC</li> </ul> </li>  <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength013+'</li> <li class="one-text-small">溶解氧</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength014+'</li> <li class="one-text-small">浊度</li> </ul> </li> <li class="one-site-water-type"> <ul class="test"> <li>'+dataObj.AvgStrength015+'</li> <li class="one-text-small">电导率</li> </ul> </li> </ul> </div> </div>';
}
  /*
   * jq点击事件
   */
  domClick(){

  }
  /*
   *直观/普通点击
   */
  showSiteName(type, elem) {
    $(elem).addClass("active").siblings(".active").removeClass("active");
    if (type == "showName") {
      $(".one-site-label-name").each(function () {
        $(this).show();
      });
    } else if (type == "normal") {
      $(".one-site-label-name").each(function () {
        $(this).hide();
      });
    }
  }
  /*
   * 获取站点信息
   */
  getMapSiteInfo(){
    this.clearData();
    this.clearAllLabel();
    // if(this.isSingle){
    //   this.clearAllLabel()
    // }else{
    //   this.clearPartLabel(this.siteType);
    // }
    this.wxGridService.getMapSiteData(this.siteType).subscribe(
      result => this.responseUtil.success(result,this.handleSiteResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleSiteResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.batchAddSite(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  batchAddSite = (data) =>{
    if(data && data.hasOwnProperty("siteList") && data.siteList.length){
      let center = data.centerSite || data.siteList[0];
      let centerPoint;
      if(center.hasOwnProperty("Longitude")){
        centerPoint = new BMap.Point(center.Longitude,center.Latitude);  // 创建点坐标
      }else{
        centerPoint = new BMap.Point(center.lng,center.lat);  // 创建点坐标
      }
      this.map.centerAndZoom(centerPoint,this.map.getZoom());
      if(data.siteList.length){
        data.siteList.forEach((dataObj,i) =>{
          dataObj.pointType = this.siteType;
          dataObj.longitude = dataObj.Longitude;
          dataObj.latitude = dataObj.Latitude;
          this.mapLabel(dataObj);
        });
        if(data.siteList.length>this.count){
          this.nullSiteList = "加载更多"
        }else{
          this.nullSiteList = "暂无更多数据";
        }
        this.siteCacheArr = data.siteList;
        this.siteArr = data.siteList.slice(0,this.clickNum * this.count);
      }else{
        this.nullSiteList = "暂无更多数据"
      }
    }else{
      this.nullSiteList = "暂无数据";
    }
  };
  /*
   * 获取网格信息
   */
  getMapGridInfo(){
    this.clearData();
    if(this.isSingle){
      this.clearAllLabel()
    }else{
      this.clearPartLabel(this.gridType);
    }
    let regionName : string = "";
    if(this.searchName){
      regionName = this.searchName.nativeElement.value;
    }
    regionName = encodeURI(encodeURI(regionName));
    this.wxGridService.getMapGridData(this.gridType,regionName).subscribe(
      result => this.responseUtil.success(result,this.handleGridResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleGridResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.batchAddGrid(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  batchAddGrid = (data) =>{
    if(data && data.length){
      data.forEach((dataObj,i) =>{
        dataObj.pointType = this.siteType;
        dataObj.gridType = this.gridType;
        this.mapLabel(dataObj);
      });
      if(data.length>this.count){
        this.nullSiteList = "加载更多"
      }else{
        this.nullSiteList = "暂无更多数据"
      }
      this.siteCacheArr = data;
      this.map.centerAndZoom(new BMap.Point(data[0].longitude,data[0].latitude),this.map.getZoom());
      this.siteArr = data.slice(0,this.clickNum * this.count);
    }else{
      this.nullSiteList = "暂无数据";
    }
  };
  /*
   * 获取网格详细信息
   */
  getMapGridDetailInfo(regionCode){
    this.wxGridService.getMapGridDetailData(regionCode).subscribe(
      result => this.responseUtil.success(result,this.handleGridDetailResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleGridDetailResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.batchAddGridDetail(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  batchAddGridDetail = (data) =>{
    let option = {offset:new BMap.Size(5,-26),width:600};
    let html = this.gridWindowHtml(data,this.gridDetailObj.regionName);
    let point = new BMap.Point(this.gridDetailObj.longitude,this.gridDetailObj.latitude);
    let infoWindow = new BMap.InfoWindow(html,option);
    infoWindow.addEventListener("open",function(open){
      $(".gridDuty").click(function(){
        let gridDutyHtml = "";
        if(this.gridDetailObj.hasOwnProperty("remark") && this.gridDetailObj.remark){
          gridDutyHtml = '<div>'+this.gridDetailObj.remark+'</div>';
        }else{
          gridDutyHtml = '<div>暂无数据</div>';
        }
        $(".one-map-grid-duty").show().children(".one-map-grid-duty-body").html(gridDutyHtml);
      }.bind(this));
      $(".gridPeopleDuty").click(function(e){
        let dutyListType = $(e.target).data("list");
        let gridDutyListHtml = "";
        if(data[dutyListType][0].hasOwnProperty("dutyDetails") && data[dutyListType][0].dutyDetails){
          gridDutyListHtml = '<div>'+data[dutyListType][0].dutyDetails+'</div>';
        }else{
          gridDutyListHtml = '<div>暂无数据</div>';
        }
        $(".one-map-grid-duty").show().children(".one-map-grid-duty-body").html(gridDutyListHtml);
      }.bind(this))
    }.bind(this));
    infoWindow.addEventListener("close",function(open){
      $(".one-map-grid-duty").hide();
    }.bind(this));
    this.gridDetailObj.type == "list" && this.map.centerAndZoom(point,this.map.getZoom());
    this.map.openInfoWindow(infoWindow,point);
  };
  /*
   * 获取网格重点企业
   */
  getGridEnterprise(){
    this.clearData();
    this.clearAllLabel();
    // if(this.isSingle){
    //   this.clearAllLabel();
    // }else{
    //   this.clearPartLabel(this.siteType);
    // }
    this.wxGridService.getGridEnterprise().subscribe(
      result => this.responseUtil.success(result,this.handleEnterpriseResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleEnterpriseResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.batchAddGrid(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  /*
  *地图标题控件
   */
  TitleControl (){
    this.defaultAnchor = BMAP_ANCHOR_TOP_RIGHT;
    this.defaultOffset = new BMap.Size(30, 200);
  };
  mapTitle(){
    this.TitleControl.prototype = new BMap.Control();
    this.TitleControl.prototype.initialize = function(map){
      let div = document.createElement("div");
      map.getContainer().appendChild(div);
      div.className = "one-map-title";
      $(div).html('温县防治作战图');
      return div;
    };
    let titleControl = new this.TitleControl();
    // 添加到地图当中
    this.map.addControl(titleControl);
  }

  /*
   *加载数据
   */
  loadData(){
    this.clickNum++;
    if(this.clickNum>Math.ceil(this.siteCacheArr.length/15)){
      return false;
    }else{
      let sliceArr = this.siteCacheArr.slice((this.clickNum-1)*15,this.clickNum*15);
      this.siteArr = this.siteArr.concat(sliceArr);
      if(sliceArr.length<15 || this.clickNum == Math.ceil(this.siteCacheArr.length/15)){
        this.nullSiteList = "暂无更多数据";
        return false;
      }else{
        this.nullSiteList = "加载更多";
      }
    }
  }

  /*
   * 获取巡检人员数据
   */
  getTrackDeviceList (){
    this.wxGridService.getTrackDeviceList(this.trackDeviceType).subscribe(
      result => this.responseUtil.success(result,this.handleTrackDeviceResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleTrackDeviceResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.showTrackDeviceList(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  showTrackDeviceList(datas){
    if(datas.length){
      this.testLushuData = {};
      if(this.trackType == "history"){
        this.trackHistoryArr = datas;
        this.trackHistoryArr.forEach((device,i)=>{
          if(i<3){
            this.testLushuData[device.deviceCode] = {arrPoints : this.testLushuPoint[i],color:this.testLushuColor[i]}
          }
        })
      }else{
        datas.forEach((data,i)=>{
          if(data.deviceStatus == 'online'){
            data.status = "在线";
            data.statusClass = "on";
          }else{
            data.status = "离线";
            data.statusClass = "off";
          }
        });
        this.trackRealArr = datas;
      }
    }
  }
  /*
   * 巡检详情里的点击事件
   */
  filterChooseClick(elem){
    if($(elem).hasClass("filter")){
      $(elem).html("所有").removeClass("filter").addClass("action").parents(".choose-btn").next().find("input").each(function(){
        $(this).is(':checked')?$(this).parent().show():$(this).parent().hide();
      })
    }else{
      $(elem).html("已选").removeClass("action").addClass("filter").parents(".choose-btn").next().find("input").each(function(){
        $(this).parent().show();
      })
    }
  }
  trackRealClick(track,elem){
    if(!$(elem).prev().is(':checked')){
      let text = track.deviceName;
      let lng = track.lng;
      let lat = track.lat;
      let img = track.deviceStatus == "online"?"ico-polling-online.png":"ico-polling-outline.png";
      let markerInfo = {point:new BMap.Point(lng,lat),img:img,content:text,data:track};
      this.map.panTo(new BMap.Point(lng,lat)); //移动地图到当前点
      this.realMarker.marker.push(this.trackMarker(markerInfo));
      this.realMarker.id.push('real-'+track.deviceCode);
    }else{
      if(this.realMarker.marker.length){
        let markerIndex = this.realMarker.id.indexOf('real-'+track.deviceCode);
        this.map.removeOverlay(this.realMarker.marker[markerIndex]);
        this.realMarker.marker.splice(markerIndex,1);
        this.realMarker.id.splice(markerIndex,1) ;
      }
    }
  }
  trackHistoryClick(track,elem){
    this.lushuClickElem = elem;
    if(!$(elem).prev().is(':checked')){
      this.lushuOverlays.push(track.deviceCode);
      this.trackDeviceCode = track.deviceCode;
      this.trackSearchDate = $(this.pathDate.nativeElement).val();
      this.trackHistoryData();
    }else{
      if(this.lushuOverlays.indexOf(track.deviceCode)!=-1){
        let lushuIndex = this.lushuOverlays.indexOf(track.deviceCode);
        let clearLushu = this.lushuData[lushuIndex];
        this.map.removeOverlay(this.lushuStartAndEnd[2*lushuIndex]);
        this.map.removeOverlay(this.lushuStartAndEnd[2*lushuIndex+1]);
        this.map.removeOverlay(this.lushuLine[lushuIndex]);
        this.lushuOverlays.splice(lushuIndex,1);
        this.lushuData.splice(lushuIndex,1);
        this.lushuLine.splice(lushuIndex,1);
        this.lushuStartAndEnd.splice(2*lushuIndex,2);
        if($(elem).siblings(".play").find(".fa").hasClass("fa-pause")){
          $(elem).siblings(".play").find(".fa").removeClass("fa-pause").addClass("fa-play");
          clearLushu.stop();
          this.deleteLushuIcon();
        }
      }
    }
  }
  //删除路书运动ICON
  deleteLushuIcon(){
    if(this.map.getOverlays().length>=3*this.lushuData.length){
      let carOverlays = this.map.getOverlays().length - 3*this.lushuData.length;
      carOverlays>0 && this.map.removeOverlay(this.lushuSpotrIcon[0]);
      carOverlays>1 && this.map.removeOverlay(this.map.getOverlays()[this.map.getOverlays().length-1]);
      this.lushuSpotrIcon = []
    }
  }
  //清除路书中的所有数据
  clearLushuData(){
    this.map.clearOverlays();
    let presentDataBox = this.trackType=="real"?$(".trackReal"):$(".trackHistory");
    presentDataBox.find(".choose-btn").next().find("input").each(function(){
      this.checked =false;
    });
    this.trackType=="history" && $(".trackHistory .fa-pause").removeClass("fa-pause").addClass("fa-play");
    this.lushuOverlays = [];
    this.lushuData = [];
    this.lushuLine = [];
    this.lushuStartAndEnd = [];
    this.lushuSpotrIcon = [];
    this.realMarker = {marker:[],id:[]}
  }
  /*
   * 格式化日期
   */
  formatDateInfo(elem){
    //配置信息
    let config = {
      singleDatePicker: true,
      locale:{
        format:"YYYY-MM-DD",
        separator: " 至 ",
        applyLabel : '确定',
        cancelLabel : '取消',
        fromLabel: '从',
        toLabel: '到',
        weekLabel: 'W',
        customRangeLabel: 'Custom Range',
        daysOfWeek:["日","一","二","三","四","五","六"],
        monthNames: ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],
        firstDay:1
      },
      startDate: new Date(),
      endDate: new Date(),
      maxDate: new Date()
    };
    $(elem).daterangepicker(config).on('hide.daterangepicker', () => {
      this.clearLushuData();
    });
  }
  /*
   * 巡检轨迹回放的点击事件
   */
  trackSportClick(elem,track){
    let lushuIndex = this.lushuOverlays.indexOf(track.deviceCode);
    let lushu = this.lushuData[lushuIndex];
    if($(elem).siblings("input:checked").length && $(elem).children(".fa").hasClass("fa-play")){
      $(elem).parent().siblings().each(function(i,elem){
        if($(elem).find(".fa").hasClass("fa-pause")){
          $(elem).find(".fa").removeClass("fa-pause").addClass("fa-play");
          let clearIndex = this.lushuOverlays.indexOf(track.deviceCode);
          let clearLushu = this.lushuData[clearIndex];
          clearLushu.stop();
          this.deleteLushuIcon();
        }
      }.bind(this));
      if(lushu){
        $(elem).children(".fa").removeClass("fa-play").addClass("fa-pause");
        lushu.start();
      }
      this.lushuSpotrIcon.push(this.map.getOverlays()[this.map.getOverlays().length-1]);
    }else if($(elem).siblings("input:checked").length && $(elem).children(".fa").hasClass("fa-pause")){
      $(elem).children(".fa").removeClass("fa-pause").addClass("fa-play");
      lushu.stop();
      this.deleteLushuIcon();
    }
  }
  /*
   * 获取轨迹回放数据
   */
  trackHistoryData(){
    this.wxGridService.getTrackDeviceData(this.trackDeviceCode,this.trackSearchDate).subscribe(
      result => this.responseUtil.success(result,this.handleTrackDeviceLineResult),
      message => this.responseUtil.error(message)
    )
  }
  private handleTrackDeviceLineResult = (result: MsgResult) =>{
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.showTrackDeviceLine(result.data);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  };
  showTrackDeviceLine(data) {
    if(data && data.trackList.length){
      let lushuPoint = data.trackList;
      let arrCachePoints = [];
      let arrPoints = [];
      let convertor = new BMap.Convertor();
      $.each(lushuPoint,(i,point)=>{
        console.log(new BMap.Point(point.lng,point.lat));
        convertor.translate([new BMap.Point(point.lng,point.lat)], 1, 5, (data) =>{
          if(data.status == 0){
            // arrPoints.push(data.points[0]);
            arrPoints.push(new BMap.Point(data.points[0].lng.toFixed(3),data.points[0].lat.toFixed(3)));
            if(i<5 ){
              console.log( (point.lng+" "+point.lat));
              console.log(data.points[0].lng.toFixed(3),data.points[0].lat.toFixed(3));
            }
            if(i == (lushuPoint.length-1)){
              console.log(arrPoints);
              this.lushuPath(arrPoints,"#48ab5d");
              let p1Info = {point:arrPoints[0],img:"ico-startPoint.png",content:"起点",type:"history"};
              let p2Info = {point:arrPoints[arrPoints.length-1],img:"ico-endPoint.png",content:"终点",type:"history"};
              this.trackMarker(p1Info); //起点
              this.trackMarker(p2Info); //终点
            }
          }
        });
      });
      // this.lushuPath(arrCachePoints,"#48ab5d");
      // let count = Math.ceil(lushuPoint.length/10);
      // console.log(count);
      // let i =1;
      // while (i<=count){
      //   let points = arrCachePoints.slice(0,i*10);
      //   let convertor = new BMap.Convertor();
      //   convertor.translate(points, 1, 5, (data) =>{
      //     console.log(data.points);
      //     arrPoints.concat(data.points);
      //     if(i == count){
      //       console.log(arrPoints);
      //       this.lushuPath(data.points,"#48ab5d");
      //       let p1Info = {point:data.points[0],img:"ico-startPoint.png",content:"起点",type:"history"};
      //       let p2Info = {point:data.points[data.points.length-1],img:"ico-endPoint.png",content:"终点",type:"history"};
      //       this.trackMarker(p1Info); //起点
      //       this.trackMarker(p2Info); //终点
      //     }
      //   });
      //   i++;
      // }

      // convertor.translate(arrPoints, 1, 5, (data) =>{
      //     arrPoints.push(data.points[0]);
      //     arrPoints.push(new BMap.Point(data.points[0].lng.toFixed(3),data.points[0].lat.toFixed(3)));
      //     if(i<5 ){
      //       console.log( (point.lng+" "+point.lat));
      //       console.log(data.points[0].lng.toFixed(3),data.points[0].lat.toFixed(3));
      //     }
      //     if(i == (lushuPoint.length-1)){
      //       this.lushuPath(data.points,"#48ab5d");
      //     }
      // });
    }else{
      $(this.lushuClickElem).prev()[0].checked = false;
      this.dialogService.info("暂无巡检路线");
    }

    // /*测试*/
    // if(this.testLushuData.hasOwnProperty(this.trackDeviceCode)){
    //   let lushuPoint = this.testLushuData[this.trackDeviceCode].arrPoints;
    //   let color = this.testLushuData[this.trackDeviceCode].color;
    //   let arrPoints = [];
    //   $.each(lushuPoint,function(i,point){
    //     arrPoints.push(new BMap.Point(point.lng,point.lat));
    //   });
    //   let p1Info = {point:arrPoints[0],img:"ico-startPoint.png",content:"起点",type:"history"};
    //   let p2Info = {point:arrPoints[arrPoints.length-1],img:"ico-endPoint.png",content:"终点",type:"history"};
    //   this.trackMarker(p1Info); //起点
    //   this.trackMarker(p2Info); //终点
    //   this.lushuPath(arrPoints,color);
    // }else{
    //   $(this.lushuClickElem).prev()[0].checked = false;
    //   this.dialogService.info("暂无巡检路线");
    // }
  }

  /*
   * 批量转换坐标
   */
 // batchChangePoint(){
 //   setTimeout(function(){
 //     var convertor = new BMap.Convertor();
 //     var pointArr = [];
 //     pointArr.push(ggPoint);
 //     convertor.translate(pointArr, 1, 5, translateCallback)
 //   }, 100);
 // }

  // 路书路线显示
  lushuPath(arrPois,color){
    let lushu;
    let polyLine  = new BMap.Polyline(arrPois, {strokeColor: color});
    this.map.addOverlay(polyLine);   /*颜色*/
    this.map.setViewport(arrPois);   /*调整视野*/

    lushu = new BMapLib.LuShu(this.map,arrPois,{
      // defaultContent:" ",//提示框的默认内容
      //                    autoView:true,//是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
      icon  : new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/car.png', new BMap.Size(52,26),{anchor : new BMap.Size(27, 13)}),
      speed: 200,
      enableRotation:true,//是否设置marker随着道路的走向进行旋转
      landmarkPois: [  //数组必须存在
        //特殊点设置
        //                        {lng:116.402046,lat:39.913928,html:'aa',pauseTime:2},
        //                        {lng:116.376683,lat:39.913282,html:'加油站',pauseTime:2},
        ////                        {lng:116.378477,lat:39.954493,html:'高速公路收费',pauseTime:10},
        //                        {lng:116.303499,lat:40.063862,html:'肯德基早餐',pauseTime:10}
      ]
    });
    this.lushuLine.push(polyLine);
    this.lushuData.push(lushu);
  }
  //    巡检监测标注
  trackMarker(markerObj){
    let startAngEnd = new BMap.Label(" ",    //为lable填写内容
      {offset:new BMap.Size(-24,-50),                  //label的偏移量，为了让label的中心显示在点上
        position:markerObj.point});                                //label的位置
    startAngEnd.setStyle({                                   //给label设置样式，任意的CSS都是可以的
      maxWidth:"48px",
      width:"48px",  //宽
      display:"inline-block",
      border:"0",
      height:"59px",                //高度
      background:"url(../../../../../assets/v1/css/themes/dam/realTime/mapImg/" + markerObj.img + ") no-repeat",    //背景图片
      cursor:"pointer"
    });
    startAngEnd.setTitle(markerObj.content);               //为label添加鼠标提示
    this.map.addOverlay(startAngEnd);
    if(markerObj.type){
      this.lushuStartAndEnd.push(startAngEnd);
    }else{
      startAngEnd.setContent("<div class='one-track-label-name'>"+markerObj.content+"</div>");
      startAngEnd.addEventListener("click",function(e){
        this.infoTrackWindowEvent(markerObj.data);
      }.bind(this))
    }
    return startAngEnd;
  }
  /*
   * 信息窗口
   */
  infoTrackWindowEvent(dataObj){
    let option = {offset:new BMap.Size(5,-26),width:300};
    let html = "";
    html = this.trackInfoWindowHtml(dataObj);
    let infoWindow = new BMap.InfoWindow(html,option);
    let point = new BMap.Point(dataObj.lng,dataObj.lat);
    this.map.openInfoWindow(infoWindow,point);
  }
  //信息窗口html
  trackInfoWindowHtml(dataObj){
    return `
      <div class="one-info-window">
         <div class="one-info-content">
           <div class="one-info-content-header">               
             <span>巡检人员信息</span>
           </div>    
           <div class="one-info-content-body one-grid-content-body" style="padding: 0 10px;">        
             <ul class="list-inline">
               <li>公司名称：</li>
               <li>${dataObj.companyName || "-"}</li>          
             </ul>       
             <ul class="list-inline">
               <li>司机名称：</li>    
               <li>${dataObj.driverName || "-"} </li>           
             </ul>
             <ul class="list-inline">
               <li>车牌号：</li>
               <li>${dataObj.carCode || "-"} </li>           
             </ul>
             <ul class="list-inline">
               <li>联系电话：</li>
               <li>${dataObj.phone || "-"}</li>          
             </ul>     
           </div>
         </div>
      </div>
    `;
  }
  trackStaffClick(type){
    this.trackDeviceType = type;
    this.clearData();
    this.clearAllLabel();
    this.clearLushuData();
    this.getTrackDeviceList();
  }
  trackDropDownClick(elem){
    if($(elem).children(".dropdown-menu").css("display") == "block"){
      $(elem).children(".dropdown-menu").hide();
    }else{
      $(elem).children(".dropdown-menu").show();
    }
  }
  trackDropDownLeave(elem){
    $(elem).children(".dropdown-menu").hide();
  }
  trackShrinkClick(){
    let presentDataBox = this.trackType=="real"?$(".trackReal"):$(".trackHistory");
    if(presentDataBox.css("display") == "none"){
      $(this).children(".fa").removeClass("fa-chevron-down").addClass("fa-chevron-up");
      presentDataBox.slideDown(300);
    }else{
      $(this).children(".fa").removeClass("fa-chevron-up").addClass("fa-chevron-down");
      presentDataBox.slideUp(300);
    }
  }
  trackTypeClick(type){
    this.trackType = type;
    this.trackDeviceType = "allDeviceType";
    if(type=="history"){
      $("#routeArea").children(".trackHistory").show().parent().children(".trackReal").hide();
    }else{
      $("#routeArea").children(".trackHistory").hide().parent().children(".trackReal").show();
    }
    this.clearLushuData();
    this.getTrackDeviceList();
  }
}
